import {getGeneratorVoByIdUsingGet,} from '@/services/backend/generatorController';
import {useModel, useParams} from '@@/exports';
import {AlipayCircleOutlined, EditOutlined, WechatOutlined} from '@ant-design/icons';
import {ActionType, PageContainer} from '@ant-design/pro-components';
import {Button, Card, Col, Image, message, Row, Space, Tabs, Tag, Typography} from 'antd';
import moment from 'moment';
import React, {useEffect, useRef, useState} from 'react';
import ModelConfig from "@/pages/Generator/Detail/components/ModelConfig";
import {waitTimePromise} from "@/pages/Admin/UserManage";
import CreateModal from "@/pages/Generator/Detail/components/CreateModal";
// @ts-ignore
import {IContact} from "react-jwchat";
import MyChat from "@/pages/Generator/Detail/components/MyChat";
import ReportModal from "@/pages/Generator/Detail/components/ReportModal";

/**
 * 生成器详情页
 * @constructor
 */
const GeneratorDetailPage: React.FC = () => {
  const { id } = useParams();

  const [loading, setLoading] = useState<boolean>(false);
  // @ts-ignore
  const [data, setData] = useState<API.GoodsResult>({});
  const [createModalVisible, setCreateModalVisible] = useState<boolean>(false);
  const [createChatVisible, setCreateChatVisible] = useState<boolean>(false);
  const [createReportVisible, setCreateReportVisible] = useState<boolean>(false);
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState ?? {};
  const actionRef = useRef<ActionType>();
  const userId = currentUser?.id;
  const sendUser=currentUser?.userAccount

  /**
   * 加载数据
   */
  const loadData = async () => {
    if (!id) {
      return;
    }
    setLoading(true);
    try {
      const res = await getGeneratorVoByIdUsingGet({
        id,
      });
      setData(res || {});
    } catch (error: any) {
      message.error('获取数据失败，' + error.message);
    }
    setLoading(false);
  };

  useEffect(() => {
    loadData();
  }, [id]);

  /**
   * 标签列表视图
   * @param tags
   */
  const tagListView = (tag?: string) => {
    if (!tag) {
      return <></>;
    }

    return (
      <div style={{ marginBottom: 8 }}>
        <Tag key={tag}>{tag}</Tag>
      </div>
    );
  };

  /**
   * 下载按钮
   */
  const PayButton = currentUser && (
    <Button
      icon={<AlipayCircleOutlined />}
      onClick={async () => {
        window.open("http://localhost:8080/api/alipay/pay?goodsName=" + data.goodsName +"&goodsId="+data.id+ "&amount=" + data.price+"&username="+currentUser.username+"&userId="+currentUser.id)
      }}
    >
      购买
    </Button>
  );

  /**
   * 编辑按钮
   */
  const editButton = currentUser && (
      <Button
        icon={<EditOutlined />}
        onClick={() => setCreateModalVisible(true)}
      >评论</Button>
  );

  /**
   * 沟通按钮
   */
  const CommunicationButton = currentUser && (
    <Button
      icon={<WechatOutlined />}
      onClick={() => setCreateChatVisible(true)}
    >留言</Button>
  );

  /**
   * 举报按钮
   */
  const ReportButton = currentUser && (
    <Button
      icon={<WechatOutlined />}
      onClick={() => setCreateReportVisible(true)}
    >举报</Button>
  );

  return (
    <PageContainer title={<></>} loading={loading}>
      <Card>
        <Row justify="space-between" gutter={[32, 32]}>
          <Col flex="auto">
            <Space size="large" align="center">
              <Typography.Title level={3}>{data.goodsName}</Typography.Title>
              {tagListView(data.typeName)}
            </Space>
            <Typography.Title level={4}>价格：{data.price}元</Typography.Title>
            <Typography.Paragraph>{data.goodsDescription}</Typography.Paragraph>
            <Typography.Paragraph type="secondary">
              创建时间：{moment(data.createTime).format('YYYY-MM-DD hh:mm:ss')}
            </Typography.Paragraph>
            <Typography.Paragraph type="secondary">卖家：{data.username}</Typography.Paragraph>
            <div style={{ marginBottom: 24 }} />
            <Space size="middle">
              {PayButton}
              {editButton}
              {CommunicationButton}
              {ReportButton}
            </Space>
          </Col>
          <Col flex="320px">
            <Image height={350} src={data.goodsImage} />
          </Col>
        </Row>
      </Card>
      <div style={{ marginBottom: 24 }} />
      <Card>
        <Tabs
          size="large"
          defaultActiveKey={'fileConfig'}
          onChange={() => {}}
          items={[
            {
              key: 'fileConfig',
              label: '评论',
              children: <ModelConfig data={data.comments??[]} />,
            },
          ]}
        />
      </Card>
      <CreateModal
        modalVisible={createModalVisible}
        userId={userId??0}
        goodsId={data.id}
        onCancel={() => setCreateModalVisible(false)}
        onSubmit={async ()=>{
          await waitTimePromise(500);
          setCreateModalVisible(false);
          actionRef.current?.reload();
        }}
      />
      <ReportModal
        modalVisible={createReportVisible}
        userId={userId??0}
        goodsId={data.id}
        onCancel={() => setCreateReportVisible(false)}
        onSubmit={async ()=>{
          await waitTimePromise(500);
          setCreateReportVisible(false);
          actionRef.current?.reload();
        }}
      />
      <MyChat
        modalVisible={createChatVisible}
        sendName={sendUser??""}
        receiveName={data.username}
        goodsId={data.id}
        onCancel={() => setCreateChatVisible(false)}
        onSubmit={async ()=>{
          await waitTimePromise(500);
          setCreateChatVisible(false);
          actionRef.current?.reload();
        }}
      />
    </PageContainer>
  );
};

export default GeneratorDetailPage;
